package top.lyf1210.yuwenpicturebackend.manager.upload;

import cn.hutool.core.io.FileUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import top.lyf1210.yuwenpicturebackend.exception.ErrorCode;
import top.lyf1210.yuwenpicturebackend.exception.ThrowUtils;

import java.io.File;

import static top.lyf1210.yuwenpicturebackend.constant.FileConstant.*;

/**
 * @ClassNameFilePictureUpload
 * @Description TODO
 * @Author钰玟
 * @Date2025/5/9 下午4:44
 * @Version 1.0
 **/
@Service
public class FilePictureUpload extends PictureUploadTemplate{
    @Override
    protected void validPicture(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        ThrowUtils.throwIf(multipartFile==null, ErrorCode.PARAMS_ERROR,FILE_CAN_NOT_BE_NULL);
        //1.校验文件大小
        long fileSize = multipartFile.getSize();
        //不能超过 2M
        ThrowUtils.throwIf(fileSize>2*ONE_M,ErrorCode.PARAMS_ERROR,FILE_SIZE_ERROR);
        //2. 校验文件后缀
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        ThrowUtils.throwIf(!ALLOW_FILE_SUFFIX.contains(fileSuffix),ErrorCode.PARAMS_ERROR,FILE_TYPE_ERROR);
    }

    @Override
    protected String getOriginFilename(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        return multipartFile.getOriginalFilename();
    }

    @Override
    protected void processFile(Object inputSource, File file) throws Exception {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        multipartFile.transferTo(file);
    }
}
